package com.tanhua.app.service;

import cn.hutool.crypto.SecureUtil;
import com.tanhua.api.UserApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.config.template.HuanXinTemplate;
import com.tanhua.config.template.SmsTemplate;
import com.tanhua.model.pojo.User;
import com.tanhua.model.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 通过短信发送验证码
     * @param phone
     */
    public void sendSms(String phone) {
        //1、随机生成验证码
//        String code = RandomUtil.randomNumbers(6);

        //2.调用SmsTemplates发送验证码(需注入该依赖)
//        smsTemplate.sendSms(phone,code);

        //3.将发送的验证码存入到缓存中
        String code = "123456";
        redisTemplate.opsForValue().set("Login-Code-" + phone,code,5, TimeUnit.MINUTES);
    }

    /**
     * 登陆时校验验证码，并生成token
     * @param phone
     * @param code
     * @return
     */
    public Map loginVerification(String phone, String code) {
        //1.从redis缓存中得到短信发送的验证码
        String redisCode = redisTemplate.opsForValue().get("Login-Code-" + phone);

        //2.比对redis中的验证码和用户输入的验证码
        if (StringUtils.isBlank(code) || !redisCode.equals(code)){
            //验证码校验失败
            throw new BusinessException(ErrorResult.loginError());
        }
        //3.校验成功判断用书是否是新用户,通过dubbo调用远程服务userApi查询数据库是否存在该用户
        User user = userApi.findByPhone(phone);

        //默认设置用户不是新用户
        Boolean isNew = false;
        //4.若是新用户，则需要新增该用户的信息到数据库中
        if (user == null){
            //该用户不存在，为新用户，存入数据库(dubbo远程调用userApi)
            user = new User();
            user.setMobile(phone);
            user.setPassword(SecureUtil.md5("123456"));
            //通过userApi新增用户
            Long id = userApi.save(user);
            user.setId(id);

            //设置该用户是新用户
            isNew = true;

            //还需要为该新用户注册环信账号:hx+用户id
            //注册环信用户
            String hxUser = Constants.HX_USER_PREFIX + id;
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.updateUser(user);
            }else {
                throw new BusinessException(ErrorResult.huanXinError());
            }
        }

        //5.生成该用户的token
        Map map = new HashMap();
        map.put("id",user.getId());
        map.put("phone",phone);
        //调用工具类生成token
        String token = JwtUtils.getToken(map);

        //6.返回结果
        Map result = new HashMap();
        result.put("token",token);
        result.put("isNew",isNew);

        return result;
    }
}
